"""
CSPBuilder plugin

Provides setup functionality

Copyright (c) 2008 Rune M. Friborg, runef@diku.dk.
See LICENSE.txt for licensing details (GPLv2).
"""

PLUGIN_NAME = "Setup"

try:
    import cPickle as pickle
except:
    import pickle

import base64

from extensions import cspxml
from plugins.execute import *

class PluginSetup(PluginEXECUTION):

    def __init__(self, pluginManager):
        PluginEXECUTION.__init__(self, pluginManager, PLUGIN_NAME)
        self.debug_config = False
        self.configData = {}

    def activateDebug(self):
        self.debug_config = True

    def extractConfigData(self, p, path = 'main'):

        process_name = path + '.' + p['name']

        if p.has_key('config'):
            #Config
            for c in p['config']:
                key = process_name + '.' + c['process']
                if (not self.configData.has_key(key)):
                    self.configData[key] = c['data']
       
        if p.has_key('PROCESSLINKS'):
            for each in p['PROCESSLINKS']:
                self.extractConfigData(each['PROCESS'], process_name)

        if p.has_key('PROCESSES'):
            for each in p['PROCESSES']:
                self.extractConfigData(each, process_name)

        return p


    def editParamList(self, processObj, L, D):

        if (self.configData.has_key(processObj.name)):
            configData= pickle.loads(base64.b64decode(self.configData[processObj.name]))
            if (self.debug_config):
                print processObj.name + ' : ' + str(configData)
            
            D['data'] = configData
        
        return (L,D)


    def loadTag(self, node, att):
        # Does processlink contain any process?
        if (att.has_key('PROCESS')):
            # If so, then load config
            for config in node.childNodes:
                if (config.nodeName == 'config'):
                    if (att['PROCESS'].has_key('config')):
                        att['PROCESS']['config'].append(cspxml.getAttrList(config))
                    else:
                        att['PROCESS']['config'] = [cspxml.getAttrList(config)]
        return att


def load(pluginManager):

    p = PluginSetup(pluginManager)
    
    p.addCommandLineArg('-dl', '--debug-config', p.activateDebug, '  -dl, --debug-config      Print all configured components\n')
    p.addCSPFileProcessing(node_PROCESS_LINK, p.loadTag)
    p.addCSPTreeProcessing(p.extractConfigData)
    p.addToProcessCreation(p.editParamList)

    pluginManager.addPlugin(p)
